import React from 'react'
import Docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import { saveAs } from 'file-saver'
import ImageModule from 'docxtemplater-image-module-free'

export default function ({ templatePath, outputName, data }) {
  const exportDocx = async () => {
    // 1. 加载模板
    const templateRes = await fetch(templatePath)
    const templateBuffer = await templateRes.arrayBuffer()

    // 2. 图片预处理
    const imageDict = {}
    for (const [key, imgSrc] of Object.entries(data.images)) {
      const imgRes = await fetch(imgSrc)
      imageDict[key] = await imgRes.arrayBuffer()
      console.log(imageDict[key])
    }

    // 3. 初始化处理器
    const zip = new PizZip(templateBuffer)
    const doc = new Docxtemplater(zip, {
      modules: [
        new ImageModule({
          getImage: (tag) => imageDict[tag],
          getSize: () => [400, 300], // 固定图片尺寸
        }),
      ],
    })

    // 4. 渲染并导出
    doc.render(data)
    // doc.render()
    const blob = doc.getZip().generate({
      type: 'blob',
      mimeType:
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    })
    saveAs(blob, `${outputName}.docx`)
  }

  return <button onClick={exportDocx}>导出文档</button>
}
